package com.ler.fast.util;

import com.alibaba.fastjson.JSONObject;
import java.io.IOException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

/**
 * http 工具类
 *
 * @author lww
 */
@Slf4j
public class HttpUtils {

    private static final String ENCODE = "UTF-8";

    private HttpUtils() {
    }

    /**
     * 向指定URL发送GET方法的请求 http
     *
     * @param url     发送请求的URL
     * @param param   请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
     * @param headers 可为null
     * @return URL 所代表远程资源的响应结果
     */
    public static String sendGetHttp(String url, String param, Map<String, String> headers) {
        HttpGet httpGet = new HttpGet(StringUtils.isBlank(param) ? url : url + "?" + param);
        headers = initHeader(headers);
        //设置header
        for (Map.Entry<String, String> entry : headers.entrySet()) {
            httpGet.setHeader(entry.getKey(), entry.getValue());
        }
        String content = null;
        try (CloseableHttpClient closeableHttpClient = HttpClientBuilder.create().build()) {
            CloseableHttpResponse httpResponse = closeableHttpClient.execute(httpGet);
            HttpEntity entity = httpResponse.getEntity();
            content = EntityUtils.toString(entity, ENCODE);
        } catch (IOException e) {
            log.error("HttpRequest_getForm_e:{}", e);
        }
        return content;
    }

    /**
     * 向指定URL发送GET方法的请求 https
     *
     * @param url     发送请求的URL
     * @param param   请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
     * @param headers 可为null
     * @return URL 所代表远程资源的响应结果
     */
    public static String sendGetHttps(String url, String param, Map<String, String> headers) {
        HttpGet httpGet = new HttpGet(StringUtils.isBlank(param) ? url : url + "?" + param);
        headers = initHeader(headers);
        //设置header
        for (Map.Entry<String, String> entry : headers.entrySet()) {
            httpGet.setHeader(entry.getKey(), entry.getValue());
        }
        String content = null;
        try (CloseableHttpClient closeableHttpClient = sslHttpClientBuild()) {
            CloseableHttpResponse httpResponse = closeableHttpClient.execute(httpGet);
            HttpEntity entity = httpResponse.getEntity();
            content = EntityUtils.toString(entity, ENCODE);
        } catch (IOException e) {
            log.error("HttpRequest_getForm_e:{}", e);
        }
        return content;
    }

    /**
     * 向指定 URL 发送POST方法的请求 form参数 http
     *
     * @param url     发送请求的 URL
     * @param param   请求参数，请求参数可以 ?name1=value1&name2=value2 拼在url后，也可以放在param中。
     * @param headers 可为null
     * @return 所代表远程资源的响应结果
     */
    public static String sendPostFormHttp(String url, Map<String, String> param, Map<String, String> headers) {
        HttpPost httpPost = new HttpPost(url);
        headers = initHeader(headers);
        headers.put("Content-Type", "application/x-www-form-urlencoded");
        for (Map.Entry<String, String> entry : headers.entrySet()) {
            httpPost.setHeader(entry.getKey(), entry.getValue());
        }
        String content = null;
        List<NameValuePair> pairList = new ArrayList<>();
        if (param != null) {
            for (Map.Entry<String, String> entry : param.entrySet()) {
                pairList.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
            }
        }
        try (CloseableHttpClient closeableHttpClient = HttpClientBuilder.create().build()) {
            httpPost.setEntity(new UrlEncodedFormEntity(pairList, ENCODE));
            CloseableHttpResponse httpResponse = closeableHttpClient.execute(httpPost);
            HttpEntity entity = httpResponse.getEntity();
            content = EntityUtils.toString(entity, ENCODE);
        } catch (IOException e) {
            log.error("HttpRequest_getForm_e:{}", e);
        }
        return content;
    }

    /**
     * 向指定 URL 发送POST方法的请求 form参数 https
     *
     * @param url     发送请求的 URL
     * @param param   请求参数，请求参数可以 ?name1=value1&name2=value2 拼在url后，也可以放在param中。
     * @param headers 可为null
     * @return 所代表远程资源的响应结果
     */
    public static String sendPostFormHttps(String url, Map<String, String> param, Map<String, String> headers) {
        HttpPost httpPost = new HttpPost(url);
        headers = initHeader(headers);
        headers.put("Content-Type", "application/x-www-form-urlencoded");
        for (Map.Entry<String, String> entry : headers.entrySet()) {
            httpPost.setHeader(entry.getKey(), entry.getValue());
        }
        String content = null;
        List<NameValuePair> pairList = new ArrayList<>();
        if (param != null) {
            for (Map.Entry<String, String> entry : param.entrySet()) {
                pairList.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
            }
        }
        try (CloseableHttpClient closeableHttpClient = sslHttpClientBuild()) {
            httpPost.setEntity(new UrlEncodedFormEntity(pairList, ENCODE));
            CloseableHttpResponse httpResponse = closeableHttpClient.execute(httpPost);
            HttpEntity entity = httpResponse.getEntity();
            content = EntityUtils.toString(entity, ENCODE);
        } catch (IOException e) {
            log.error("HttpRequest_getForm_e:{}", e);
        }
        return content;
    }

    /**
     * 发送post，参数为json字符串 放在body中 requestBody http
     *
     * @param url     url
     * @param params  参数
     * @param headers 可为null
     */
    public static String sendPostJsonHttp(String url, JSONObject params, Map<String, String> headers) {
        HttpPost httpPost = new HttpPost(url);
        headers = initHeader(headers);
        headers.put("Content-Type", "application/json");
        for (Map.Entry<String, String> entry : headers.entrySet()) {
            httpPost.setHeader(entry.getKey(), entry.getValue());
        }
        StringEntity stringEntity = new StringEntity(params.toString(), ENCODE);
        httpPost.setEntity(stringEntity);
        String content = null;
        try (CloseableHttpClient closeableHttpClient = HttpClientBuilder.create().build()) {
            CloseableHttpResponse httpResponse = closeableHttpClient.execute(httpPost);
            HttpEntity entity = httpResponse.getEntity();
            content = EntityUtils.toString(entity, ENCODE);
            closeableHttpClient.close();
        } catch (IOException e) {
            log.error("HttpUtil_sendPostJsonHttp_e:{}", e);
        }
        return content;
    }

    /**
     * 发送post，参数为json字符串 放在body中 requestBody https
     *
     * @param url     url
     * @param params  参数
     * @param headers 可为null
     */
    public static String sendPostJsonHttps(String url, JSONObject params, Map<String, String> headers) {
        HttpPost httpPost = new HttpPost(url);
        headers = initHeader(headers);
        headers.put("Content-Type", "application/json");
        for (Map.Entry<String, String> entry : headers.entrySet()) {
            httpPost.setHeader(entry.getKey(), entry.getValue());
        }
        StringEntity stringEntity = new StringEntity(params.toString(), ENCODE);
        httpPost.setEntity(stringEntity);
        String content = null;
        try (CloseableHttpClient closeableHttpClient = sslHttpClientBuild()) {
            CloseableHttpResponse httpResponse = closeableHttpClient.execute(httpPost);
            HttpEntity entity = httpResponse.getEntity();
            content = EntityUtils.toString(entity, ENCODE);
            closeableHttpClient.close();
        } catch (IOException e) {
            log.error("HttpUtil_sendPostJsonHttps_e:{}", e);
        }
        return content;
    }

    private static Map<String, String> initHeader(Map<String, String> headers) {
        if (headers == null) {
            headers = new HashMap<>(16);
        }
        headers.put("accept", "*/*");
        headers.put("connection", "Keep-Alive");
        headers.put("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
        return headers;
    }

    public static CloseableHttpClient sslHttpClientBuild() {
        Registry<ConnectionSocketFactory> socketFactoryRegistry =
                RegistryBuilder.<ConnectionSocketFactory>create()
                        .register("http", PlainConnectionSocketFactory.INSTANCE)
                        .register("https", trustAllHttpsCertificates()).build();
        //创建ConnectionManager，添加Connection配置信息
        PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
        CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(connectionManager).build();
        return httpClient;
    }

    private static SSLConnectionSocketFactory trustAllHttpsCertificates() {
        SSLConnectionSocketFactory socketFactory = null;
        TrustManager[] trustAllCerts = new TrustManager[1];
        TrustManager tm = new Mitm();
        trustAllCerts[0] = tm;
        SSLContext sc;
        try {
            sc = SSLContext.getInstance("TLS");
            sc.init(null, trustAllCerts, null);
            socketFactory = new SSLConnectionSocketFactory(sc, NoopHostnameVerifier.INSTANCE);
        } catch (NoSuchAlgorithmException | KeyManagementException e) {
            log.error("HttpUtil_trustAllHttpsCertificates_e:{}", e);
        }
        return socketFactory;
    }

    static class Mitm implements TrustManager, X509TrustManager {

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }

        @Override
        public void checkServerTrusted(X509Certificate[] certs, String authType) {
            //don't check
        }

        @Override
        public void checkClientTrusted(X509Certificate[] certs, String authType) {
            //don't check
        }
    }
}
